package com.zebra.remoting;

import com.zebra.remoting.util.RemotingUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

@ChannelHandler.Sharable
public class RemotingHandler extends SimpleChannelInboundHandler {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(RemotingHandler.class);

    private CommandHandler commandHandler;
    public RemotingHandler(CommandHandler commandHandler) {
        this.commandHandler = commandHandler;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        commandHandler.handleCommand(ctx, msg);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Connection channel active: {}", RemotingUtil.parseRemoteAddress(ctx.channel()));
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Connection channel inactive: {}", RemotingUtil.parseRemoteAddress(ctx.channel()));
        super.channelInactive(ctx);
        commandHandler.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        logger.error("ExceptionCaught in connection: {}, close the connection! Cause[{}:{}]",
                ctx.channel().toString(), throwable.getClass().getSimpleName(), throwable.getMessage());
        logger.error("ExceptionCaught in connection: "+ctx.channel().toString(), throwable);
//        throwable.printStackTrace();
        ctx.channel().close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


}
